/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>

#include "lsoh_nvmem_io.h"
#include "hal_sys_param.h"

#define STR_MAX  65

#define MTD_NAME "bdinfo"
#define MTD_SERIAL_OFFSET 1024

static unsigned char serial[STR_MAX];
static const char OHOS_SERIAL[] = {"1234567890"};  // provided by OEM.

static int HalTokenIOLenMatch(nv_var_type var_type, unsigned int len)
{
    int var_len;
    var_len = get_nv_var_size(var_type);

    // 当作字符串看待，要考虑最后一个 \0
    return (var_len + 1 == len);
}

const char* HalGetSerial(void)
{
    int res;
    unsigned char* temp = NULL;

    if (!HalTokenIOLenMatch(NV_TYPE_SN, STR_MAX)) {
        return OHOS_SERIAL;
    }
    res = nv_var_read(NV_TYPE_SN, &temp);
    if (!res) {
        memset(serial, 0, STR_MAX);
        memcpy_s(serial, STR_MAX - 1, temp, STR_MAX - 1);
    }
    if (temp) {
        free(temp);
        temp = NULL;
    }
    return res ? OHOS_SERIAL : (char*)serial;
}